﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Configuration;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.UI.WebControls;
using Common.Logging;
using In.Api.Dto.HisWs;
using In.Api.Dto.LisWs;
using Newtonsoft.Json;
using OutDbContext;
using StackExchange.Redis;
using User.Api.Dto.Check;
using User.Api.Dto.Inspection;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class InspectionController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(InspectionController));
        private HzfyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new HzfyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取化验单列表
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="startDate"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetInspections")]
        public GetInspectionsResponse GetInspections(int cardId, string startDate)
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCard.FirstOrDefault(x => x.Id == cardId && x.WxUserId == azUser.UserId);
            if (card == null)
            {
                return new GetInspectionsResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡"
                };
            }


            var request = new Request4GetExamInfo();
            request.CardNo = card.CardNo;
            request.ItemType = "C";
            request.BeginDate = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd");
            request.EndDate = DateTime.Now.ToString("yyyy-MM-dd");

            Response4GetExamInfo response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetExamInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<Response4GetExamInfo>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内获取化验单列表Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                return new GetInspectionsResponse
                {
                    ResultCode = "2",
                    ResultMsg = "获取化验单列表超时"
                };
            }

            if (response.ResultCode != "0")
            {
                return new GetInspectionsResponse
                {
                    ResultCode = "3",
                    ResultMsg = response.ResultDesc
                };
            }

            List<GetInspectionsResponse.Inspection> examInfoList = new List<GetInspectionsResponse.Inspection>();
            foreach (var inspectionInfo in response.ExamList.OrderByDescending(x => x.ExamDate))
            {
                var inspection = new GetInspectionsResponse.Inspection
                {
                    Id = inspectionInfo.ExamID,
                    Name = inspectionInfo.ExamName,
                    Date = inspectionInfo.ExamDate,
                    CardNo = inspectionInfo.CardNo,
                    PatientName = inspectionInfo.PatientName,
                    PatientSex = inspectionInfo.PatientSex,
                    Status = inspectionInfo.Status,
                    Address=inspectionInfo.FetchAddress,
                    ReportDate=inspectionInfo.ReportDate,
                    ExamType=inspectionInfo.ExamType
                };
                examInfoList.Add(inspection);
            }

            return new GetInspectionsResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                IsInp = "0",
                Inspections = examInfoList.OrderBy(x => x.Status).ThenByDescending(x => x.Id).ToList()
            };

        }

        /// <summary>
        /// 获取化验单图片
        /// </summary>
        /// <param name="cardId">卡号</param>
        /// <param name="appNo"></param>
        /// <param name="status">2：图片 0：文字</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetInspectionImgUrls")]
        public GetInspectionImgUrlsResponse GetInspectionImgUrls(int cardId, string appNo, string status)
        {
            var azUser = AzUser.GetInApi(Request);
            var card = _ctx.HospCard.FirstOrDefault(x => x.Id == cardId && x.WxUserId == azUser.UserId);
            if (card == null)
            {
                return new GetInspectionImgUrlsResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到就诊卡"
                };
            }

            int reportType = 0;
            if (status == "2")
                reportType = 1;
            #region 文字报告
            if (reportType == 0) //文字报告
            {
                var request = new Request4GetExamDetail
                {
                    CardNo = card.CardNo,
                    ExamId = appNo,
                    ItemType = "C"
                };
                Response4GetExamDetail response;

                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetExamDetail", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<Response4GetExamDetail>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用获取住院检查单详情Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    return new GetInspectionImgUrlsResponse
                    {
                        ResultCode = "2",
                        ResultMsg = "获取检查单详情超时"
                    };
                }
                
                //Logger.ErrorFormat("调用 response 失败，信息：{0}", JsonConvert.SerializeObject(response));
                
                if (response.ResultCode != "0")
                {
                    return new GetInspectionImgUrlsResponse
                    {
                        ResultCode = "3",
                        ResultMsg = response.ResultDesc
                    };
                }

                return new GetInspectionImgUrlsResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    CheckItems = response.ExamItemList.Select(x => new GetInspectionImgUrlsResponse.InspectionItem
                    {
                        ItemNo = x.ItemNo,
                        ItemDate = x.ItemDate,
                        Prompt = x.Prompt,
                        Content = x.Content,
                        //todo 比标准版本多出来的字段，前端页面摆放
                        ExamItemName = x.ExamItemName,
                        LabItemName = x.LabItemName,
                        LabRepItemName = x.LabRepItemName,
                        LabRepItemNo = x.LabRepItemNo,
                        LabRepResult = x.LabRepResult,
                        LabRepUnits = x.LabRepUnits,
                        LabInd = x.LabInd,
                        LabContext = x.LabContext
                    }).ToList()
                };

            }
            #endregion
            #region 图片
            else
            {
                var request = new Request4GetExamReports {PdfReportName = appNo + ".pdf"};
                Response4GetExamReports response;
                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("LisWs/GetExamReports", request).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    response = responseMsg.Content.ReadAsAsync<Response4GetExamReports>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用获取检查单图片Api出错,信息：{0}", JsonConvert.SerializeObject(ex));

                    //获取文字详情
                    var txtRequest = new Request4GetExamDetail
                    {
                        CardNo = card.CardNo,
                        ExamId = appNo,
                        ItemType = "C"
                    };
                    Response4GetExamDetail txtResponse;

                    try
                    {
                        var httpClient = InHttpClient.GetClient();
                        var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetExamDetail", txtRequest).Result;
                        responseMsg.EnsureSuccessStatusCode();
                        txtResponse = responseMsg.Content.ReadAsAsync<Response4GetExamDetail>().Result;
                    }
                    catch (Exception ex1)
                    {
                        Logger.ErrorFormat("调用获取检查单详情Api出错,信息：{0}", JsonConvert.SerializeObject(ex1));

                        return new GetInspectionImgUrlsResponse
                        {
                            ResultCode = "2",
                            ResultMsg = "获取检查单详情超时"
                        };
                    }

                    if (txtResponse.ResultCode != "0")
                    {
                        return new GetInspectionImgUrlsResponse
                        {
                            ResultCode = "3",
                            ResultMsg = txtResponse.ResultDesc
                        };
                    }


                    return new GetInspectionImgUrlsResponse
                    {
                        ResultCode = "0",
                        ResultMsg = "",
                        CheckItems = txtResponse.ExamItemList.Select(x => new GetInspectionImgUrlsResponse.InspectionItem
                        {
                            ItemNo = x.ItemNo,
                            ItemDate = x.ItemDate,
                            Prompt = x.Prompt,
                            Content = x.Content,
                            //todo 比标准版本多出来的字段，前端页面摆放
                            ExamItemName = x.ExamItemName,
                            LabItemName = x.LabItemName,
                            LabRepItemNo = x.LabRepItemNo,
                            LabRepResult = x.LabRepResult,
                            LabRepUnits = x.LabRepUnits,
                            LabInd = x.LabInd,
                            LabContext = x.LabContext
                        }).ToList()
                    };
                }

                string pngReportPath = WebConfigurationManager.AppSettings["PngReportPath"];

                if (!pngReportPath.EndsWith("/"))
                    pngReportPath += "/";

                //读取转换后的地址
                string imagePath = pngReportPath + DateTime.Now.ToString("yyyyMMdd");
                List<string> urls = new List<string>();
                foreach (var image in response.PngReports)
                {
                    urls.Add(imagePath + "/" + image);
                }
                return new GetInspectionImgUrlsResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    ImgUrls = urls
                };
            }
            #endregion
        }


    }
}
